package it.univaq.mwt.backoffice.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import it.univaq.mwt.business.FilesService;
import it.univaq.mwt.common.business.FilesServiceFactory;
import it.univaq.mwt.model.entity.Files;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;

public class ManageFilesAction extends DownloadAction {

	protected class ByteArrayStreamInfo implements StreamInfo {

		protected String contentType;
		protected byte[] bytes;

		public ByteArrayStreamInfo(String contentType, byte[] bytes) {
			this.contentType = contentType;
			this.bytes = bytes;
		}

		public String getContentType() {
			return contentType;
		}

		public InputStream getInputStream() throws IOException {
			return new ByteArrayInputStream(bytes);
		}
	}

	@Override
	protected StreamInfo getStreamInfo(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest request, HttpServletResponse arg3)
			throws Exception {

		int id_gift = Integer.parseInt(request.getParameter("id"));

		FilesServiceFactory filesFactory = FilesServiceFactory.getInstance();
		FilesService facadeFiles = filesFactory.getFilesService();

		Files file = facadeFiles.getSingleFile(id_gift);
		String contentType = file.getMime();
		byte[] bytes = file.getData();

		return new ByteArrayStreamInfo(contentType, bytes);
	}

}
